import SkiaImageEditor, { LayerManager } from "@/components/imageEditor/SkiaImageEditor";
import type { Layer } from "@/components/imageEditor/types";

// 假设 AnimatedBottomSheet 从其他模块导入，这里需要根据实际情况替换路径
import AnimatedBottomSheet from "@/components/imageEditor/AnimatedBottomSheet";
import CropEditor from "@/components/imageEditor/CropEditor";
import FilterEditor from "@/components/imageEditor/FilterEditor";
import RotateEditor from "@/components/imageEditor/RotateEditor";
import StickerEditor from "@/components/imageEditor/StickerEditor";
import TextEditor from "@/components/imageEditor/TextEditor";

import goon from '@/assets/svg/goon.svg';
import layers from '@/assets/svg/layers.svg';
import retuen from '@/assets/svg/retuen.svg';
import {
  ScrollableToolbar,
  ToolbarItem,
} from "@/components/ui/ScrollableToolbar";
import { SvgIcon } from '@/components/ui/SvgIcon';
import {
  SelectedMediaItem,
  useMediaSelection,
} from "@/contexts/MediaSelectionContext";
import { Entypo, MaterialIcons } from '@expo/vector-icons';
import { Stack, useRouter } from "expo-router";
import React, { useEffect, useRef, useState } from "react";

import {
  Platform,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

// 编辑器选项卡
const TABS: ToolbarItem[] = [
  {
    key: "crop",
    label: "裁剪",
    icon: "crop",
  },
  {
    key: "rotate",
    label: "旋转",
    icon: "loop",
  },
  {
    key: "filter",
    label: "滤镜",
    icon: "filter",
  },
  {
    key: "text",
    label: "文字",
    icon: "text-fields",
  },
  {
    key: "mood",
    label: "贴纸",
    icon: "emoji-emotions",
  },
  {
    key: "adjust",
    label: "调整",
    icon: "tune",
  },
  {
    key: "mosaic",
    label: "马赛克",
    icon: "texture",
  },
  {
    key: "draw",
    label: "涂鸦",
    icon: "brush",
  },
];

export default function ImageProcessScreen() {
  // 媒体数据
   
  const [mediaItems, setMediaItems] = useState<SelectedMediaItem[]>([]);
  // 当前显示的图片（可以是路径字符串或Skia Image对象）
  const [currentImage, setCurrentImage] = useState<string | any>(null);
  const [imageHistory, setImageHistory] = useState<string | any[]>([]);
  const [historyIndex, setHistoryIndex] = useState<number>(-1);
  const [tab, setTab] = useState("crop");
  const [activeToolKey, setActiveToolKey] = useState<string>("");
  const [rotationAngle, setRotationAngle] = useState(0);
  const router = useRouter();
  const { selectedMedia: globalSelectedMedia } = useMediaSelection();
  const skiaImageEditorRef = useRef<React.ElementRef<typeof SkiaImageEditor>>(null);
  const insets = useSafeAreaInsets();
  // 底部弹出层
  const [showBottomSheet, setShowBottomSheet] = useState(false);
  // 图层管理器
  const [showLayerManager, setShowLayerManager] = useState(false);
  const [layersList, setLayersList] = useState<Layer[]>([]);
  // 滤镜相关状态
  const [selectedFilter, setSelectedFilter] = useState<string>("original");
  const [currentFilterData, setCurrentFilterData] = useState<any>(null);

  // 贴纸相关状态
  const [selectedSticker, setSelectedSticker] = useState<string>("");
  const [currentStickerData, setCurrentStickerData] = useState<any>(null);

  // 文字相关状态
  const [currentTextData, setCurrentTextData] = useState<any>(null);
  const [currentTextTab, setCurrentTextTab] = useState<string>("font");

  // 文字编辑器的标签页
  const TEXT_EDITOR_TABS = [
    { key: "fancy", label: "花字" },
    { key: "font", label: "字体" },
    { key: "style", label: "样式" },
    { key: "layout", label: "排版" },
  ];

  // 处理文字标签页切换
  const handleTextTabChange = (tabKey: string) => {
    setCurrentTextTab(tabKey);
  };

  // 处理文字变化
  const handleTextChange = (textData: any) => {
    console.log("文字数据:", textData);
    setCurrentTextData(textData);
    // TODO: 将文字数据传递给画布
    // skiaImageEditorRef.current?.addText(textData);
  };

  // 当图层管理器显示时，从SkiaImageEditor获取最新图层数据
  useEffect(() => {
    if (showLayerManager && skiaImageEditorRef.current) {
      const layers = skiaImageEditorRef.current.getLayers();
      setLayersList(layers);
    }
  }, [showLayerManager]);

  useEffect(() => {
    // 从全局状态获取媒体数据
    if (globalSelectedMedia && globalSelectedMedia.length > 0) {
      setMediaItems(globalSelectedMedia);
      const originalImage = globalSelectedMedia[0].url;
      setCurrentImage(originalImage);
      // 初始化历史记录，保存原始图片
      setImageHistory([originalImage]);
      setHistoryIndex(0);
    } else {
      // 没有媒体数据，返回上一页（仅在非Web平台）
      if (Platform.OS !== "web") {
        router.back();
      }
    }
  }, [globalSelectedMedia, router]);

  /**
   * 处理底部 tab 切换
   * @param newTab 新选择的标签页
   */
  const handleTabPress = (newTab: string) => {
    console.log(newTab,'newTab')
    setTab(newTab);
    setShowBottomSheet(true);
    if (newTab === "crop") {
      setActiveToolKey("crop");
    } else if (newTab === "rotate") {
      setActiveToolKey("original");
    }
  };

  // 获取当前工具栏标题
  const getCurrentToolTitle = () => {
    const currentTab = TABS.find((t) => t.key === tab);
    return currentTab ? currentTab.label : "";
  };

  /**
   * 处理底部弹出层取消操作
   */
  const handleBottomSheetCancel = () => {
    if (tab === "crop") {
    }
    // 隐藏遮罩
    setActiveToolKey("");
    setShowBottomSheet(false);
    setShowLayerManager(false); // 确保图层管理器也关闭
  };

  /**
   * 处理底部弹出层确认操作
   */
  const handleBottomSheetConfirm = () => {
    if (tab === "crop") {
      const cropResult = skiaImageEditorRef.current?.cropImage();
      if (cropResult) {
        // 保存到历史记录
        const newHistory = [...imageHistory.slice(0, historyIndex + 1), cropResult];
        setImageHistory(newHistory);
        setHistoryIndex(newHistory.length - 1);
        setCurrentImage(cropResult);
      }
    } else  if (tab === "rotate") {
      const cropResult = skiaImageEditorRef.current?.cropImage();
      if (cropResult) {
        // 保存到历史记录
        const newHistory = [...imageHistory.slice(0, historyIndex + 1), cropResult];
        setImageHistory(newHistory);
        setHistoryIndex(newHistory.length - 1);
        setCurrentImage(cropResult);
      }
    }
    // 隐藏遮罩
    setActiveToolKey("");
    setShowBottomSheet(false);
    setShowLayerManager(false); // 确保图层管理器也关闭
  };

  /**
   * 处理上一步操作
   */
  const handlePreviousStep = () => {
    if (historyIndex > 0) {
      const newIndex = historyIndex - 1;
      setHistoryIndex(newIndex);
      setCurrentImage(imageHistory[newIndex]);
    }
  };

  /**
   * 处理下一步操作
   */
  const handleNextStep = () => {
    if (historyIndex < imageHistory.length - 1) {
      const newIndex = historyIndex + 1;
      setHistoryIndex(newIndex);
      setCurrentImage(imageHistory[newIndex]);
    }
  };

  /**
   * 处理裁剪工具选择
   * @param toolKey 选中的裁剪工具key
   */
  const handleCropToolSelect = (toolKey: string) => {
    console.log("选中的工具:", toolKey);
    setActiveToolKey(toolKey);
  };

  /**
   * 处理旋转角度变化
   * @param angle 旋转角度值
   */
  const handleRotationChange = (angle: number) => {
    console.log("旋转角度:", angle);
    // 存储旋转角度，在确认时应用旋转
    setRotationAngle(angle);
    skiaImageEditorRef.current?.rotateImage(angle); 
  };

    /**
   * 处理旋转工具栏变化
   * @param angle 旋转角度值
   */
  const handleRotateEditor = (toolKey: string) => {
    console.log("旋转toolKey:", toolKey);
    if(toolKey === 'rotate_left') {
      skiaImageEditorRef.current?.rotateLeft(); 
    } else if(toolKey === 'rotate_right') {
      skiaImageEditorRef.current?.rotateRight(); 
    } else if(toolKey === 'flip_horizontal') {
      skiaImageEditorRef.current?.flipHorizontal(); 
    } else if(toolKey === 'flip_vertical') {
      skiaImageEditorRef.current?.flipVertical(); 
    }
  };

  /**
   * 处理滤镜选择
   * @param filter 选中的滤镜对象
   */
  const handleFilterSelect = (filter: any) => {
    console.log("选中的滤镜:", filter);
    setSelectedFilter(filter.key);
    setCurrentFilterData(filter);
    // TODO: 将滤镜数据传递给画布 - 等待SkiaImageEditor实现applyFilter方法
    // skiaImageEditorRef.current?.applyFilter(filter);
  };

  /**
   * 处理滤镜编辑器关闭
   */
  const handleFilterClose = () => {
    console.log("关闭滤镜编辑器");
    setShowBottomSheet(false);
  };

  /**
   * 处理贴纸选择
   */
  const handleStickerSelect = (sticker: any) => {
    console.log("选中的贴纸:", sticker);
    setSelectedSticker(sticker.key);
    setCurrentStickerData(sticker);
    // TODO: 将贴纸数据传递给画布
    // skiaImageEditorRef.current?.addSticker(sticker);
  };

  return (
    <View style={[styles.container, showBottomSheet && styles.containerDark]}>
      <Stack.Screen options={{ headerShown: false }} />
      <View style={[{ paddingTop: insets.top + 4 }]}></View>
      {!showBottomSheet && !showLayerManager && (
        <View style={[styles.customHeader]}>
          <TouchableOpacity
            style={styles.backButton}
            onPress={() => router.back()}
          >
            <MaterialIcons name="chevron-left" size={24} color="#222" />
          </TouchableOpacity>
          <View style={styles.contentButton}>
            <TouchableOpacity 
              style={[styles.backButton, historyIndex <= 0 && styles.disabledButton]} 
              onPress={handlePreviousStep}
              disabled={historyIndex <= 0}
            >
              <SvgIcon Icon={retuen} size={16} color={historyIndex <= 0 ? "#ccc" : "#222"} />
            </TouchableOpacity>
            <TouchableOpacity 
              style={[styles.backButton, { marginLeft: 10 }, historyIndex >= imageHistory.length - 1 && styles.disabledButton]} 
              onPress={handleNextStep}
              disabled={historyIndex >= imageHistory.length - 1}
            >
              <SvgIcon Icon={goon} size={16} color={historyIndex >= imageHistory.length - 1 ? "#ccc" : "#222"} />
            </TouchableOpacity>
            <TouchableOpacity style={[styles.backButton, { marginLeft: 10 }]} onPress={() => {
              console.log('点击图层管理按钮，当前状态:', showLayerManager);
              setShowBottomSheet(false); // 关闭底部弹出层
              setShowLayerManager(true);
            }}>
              <SvgIcon Icon={layers} size={16} color={'#222'} />
            </TouchableOpacity>
          </View>
          <View style={styles.leftButton}>
            <TouchableOpacity style={styles.saveButton}>
              <Text style={styles.saveButtonText}>保存</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.more}>
              <Entypo name="dots-three-vertical" size={12} color="black" />
            </TouchableOpacity>
          </View>
        </View>
      )}
      {/* 画布容器 */}
      <View style={[styles.imageContainer,showBottomSheet && styles.imageContainerWithMargin,]}>
        {currentImage ? (
          <SkiaImageEditor
            ref={skiaImageEditorRef}
            image={typeof currentImage === 'string' ? { path: currentImage } : { image: currentImage }}
            onSave={() => console.log("保存操作")}
            onCancel={() => console.log("取消操作")}
            toolKey={activeToolKey}
            marginHorizontal={showBottomSheet ? 40 : 0}
            filterData={currentFilterData}
          />
        ) : (
          <Text style={styles.emptyText}>请选择图片</Text>
        )}
      </View>
      {/* 底部 Tabs - 当弹出层或图层管理器显示时隐藏 */}
      {!showBottomSheet && !showLayerManager && (
        <ScrollableToolbar tools={TABS} currentTool={tab} onToolPress={handleTabPress} />
      )}
      {/* 底部弹出层 */}
      <AnimatedBottomSheet
        visible={showBottomSheet}
        title={getCurrentToolTitle()}
        tabs={tab === "text" ? TEXT_EDITOR_TABS : undefined}
        onTabChange={tab === "text" ? handleTextTabChange : undefined}
        onCancel={handleBottomSheetCancel}
        onConfirm={handleBottomSheetConfirm}
      >
        {tab === "crop" && <CropEditor onToolSelect={handleCropToolSelect} />}
        {tab === "rotate" && <RotateEditor onToolSelect={handleRotateEditor} onRotationChange={handleRotationChange} />}
        {tab === "filter" && ( <FilterEditor selectedFilter={selectedFilter} currentImage={typeof currentImage === 'string' ? currentImage : undefined} onFilterSelect={handleFilterSelect} onClose={handleFilterClose} />
        )}
        {tab === "mood" && (<StickerEditor onStickerSelect={handleStickerSelect} />)}
        {tab === "text" && (<TextEditor   onTextChange={handleTextChange}  currentTab={currentTextTab}/> )}
      </AnimatedBottomSheet>
      {/* 图层管理器 */}
      <LayerManager
        visible={showLayerManager}
        onClose={() => { setShowLayerManager(false) }}
        getLayers={() => skiaImageEditorRef.current?.getLayers() || []}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#E4FAF8",
  },
  containerDark: {
    backgroundColor: "#000",
  },
  imageContainer: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
    width: "100%",
    overflow: "hidden",
  },
  imageContainerWithMargin: {
    // paddingHorizontal: 40, // 边距在SkiaImageEditor内部处理
  },
  customHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingHorizontal: 16,
    paddingVertical: 12,
    backgroundColor: "transparent",
  },
  backButton: {
    width: 30,
    height: 30,
    borderRadius: 20,
    backgroundColor: "rgba(255, 255, 255, 0.9)",
    justifyContent: "center",
    alignItems: "center",
  },
  saveButton: {
    height: 30,
    alignItems: "center",
    justifyContent: "center",
    borderTopLeftRadius: 20,
    borderBottomLeftRadius: 20,
    backgroundColor: "#fff",
    paddingHorizontal: 14,
  },
  saveButtonText: {
    color: "#222",
    fontSize: 12,
    fontWeight: "600",
  },
  contentButton: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    marginLeft: 60,
  },
  leftButton: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
  },
  more: {
    height: 30,
    alignItems: "center",
    justifyContent: "center",
    borderTopRightRadius: 20,
    borderBottomRightRadius: 20,
    backgroundColor: "#fff",
    paddingHorizontal: 6,
    marginLeft: 4,
  },
  disabledButton: {
    backgroundColor: "rgba(255, 255, 255, 0.5)",
  },
  bannerImage: {
    width: "100%",
    height: "100%",
    borderRadius: 8,
  },
  emptyText: {
    fontSize: 16,
    color: "#666",
    textAlign: "center",
  },
});